<template>
  <div class="service-detail">
    <Navigation title="服务详情" />
    <div class="top">
      <div class="title">{{ serviceDetail.name }}</div>
      <div class="tag-list">
        <div class="tag">{{ serviceDetail.topParentName }}</div>
        <div class="tag">{{ serviceDetail.parentName }}</div>
      </div>
      <div class="body">
        <div class="item" v-if="serviceDetail.contentDetails.serviceTarget">
          <div class="header">
            <img src="/static/detail/object.png" alt="" />
          </div>
          <div class="adorn">
            <img src="/static/home/rectangle.svg" alt="" />
          </div>
          <div class="content">
            {{ serviceDetail.contentDetails.serviceTarget }}
          </div>
        </div>
        <div class="item" v-if="serviceDetail.contentDetails.policyStandard">
          <div class="header">
            <img src="/static/detail/policy.png" alt="" />
          </div>
          <div class="adorn">
            <img src="/static/home/rectangle.svg" alt="" />
          </div>
          <div class="content">
            {{ serviceDetail.contentDetails.policyStandard }}
          </div>
        </div>
        <div class="item" v-if="serviceDetail.contentDetails.department">
          <div class="header">
            <img src="/static/detail/department.png" alt="" />
          </div>
          <div class="adorn">
            <img src="/static/home/rectangle.svg" alt="" />
          </div>
          <div class="content">
            {{ serviceDetail.contentDetails.department }}
          </div>
        </div>
        <div class="item" v-if="serviceDetail.contentDetails.contact">
          <div class="header">
            <img src="/static/detail/contact.png" alt="" />
          </div>
          <div class="adorn">
            <img src="/static/home/rectangle.svg" alt="" />
          </div>
          <div class="content">
            {{ serviceDetail.contentDetails.contact }}
          </div>
        </div>
        <div class="item footer">
          <div class="header">
            <img src="/static/detail/method.png" alt="" />
          </div>
          <div class="adorn">
            <img src="/static/home/rectangle.svg" alt="" />
          </div>
          <div v-if="serviceDetail.contentDetails.handleLink">
            <div class="content link" @click="copyLink">
              {{ serviceDetail.contentDetails.handleLink }}
            </div>
            <div class="copy" @click="copyLink">
              <img class="icon" src="/static/icon/link.svg" alt="" />
              <div class="text">复制链接</div>
            </div>
          </div>
          <div v-if="serviceDetail.contentDetails.miniProgramCode1 || serviceDetail.contentDetails.miniProgramCode2">
            <div class="tips">点击下方链接跳转</div>
            <div class="content link" @click="gotoMiniProgram(serviceDetail.contentDetails.miniProgramCode1)">
              {{ serviceDetail.contentDetails.miniProgramCode1 }}
            </div>
            <div class="content link" @click="gotoMiniProgram(serviceDetail.contentDetails.miniProgramCode2)">
              {{ serviceDetail.contentDetails.miniProgramCode2 }}
            </div>
          </div>
          <div class="code" v-if="serviceDetail.contentDetails.qrCode">
            <image
              class="code-img"
              :src="handleProxy(serviceDetail.contentDetails.qrCode)"
              @click="viewQRCode"
			  mode="widthFix"
              :show-menu-by-longpress="true"
            ></image>
            <div class="code-text">长按识别二维码或者保存到相册</div>
          </div>
          <div class="attachment" v-if="serviceDetail.contentDetails.otherInfo">
            <div class="content">
              {{ serviceDetail.contentDetails.otherInfo }}
            </div>
          </div>
          <!-- 附件列表 -->
          <div class="attachment-list" v-if="attachmentList && attachmentList.length > 0">
            <div class="attachment-title">相关附件</div>
            <div
              class="attachment-item"
              v-for="(item, index) in attachmentList"
              :key="index"
              @click="openAttachment(item)"
            >
              <!-- 如果是图片，只显示大尺寸缩略图，点击可预览 -->
              <template v-if="isImageFile(item.name)">
                <div class="attachment-image-preview-large">
                  <image 
                    :src="handleProxy(item.url)" 
                    class="attachment-thumbnail-large" 
                    :lazy-load="true"
                    mode="widthFix"
                  />
                </div>
              </template>
              <!-- 如果不是图片，显示文件图标和详细信息 -->
              <template v-else>
                <div class="attachment-icon">
                  <view class="file-icon" :class="getFileIconClass(item.name)">
                    {{ getFileExtension(item.name) }}
                  </view>
                </div>
                <div class="attachment-info">
                  <div class="attachment-name">{{ item.name }}</div>
                  <div class="attachment-size">{{ formatFileSize(item.size) }}</div>
                </div>
                <div class="view-text">查看</div>
              </template>
            </div>
          </div>
          <div
            class="empty-box"
            v-if="
              !serviceDetail.contentDetails.handleLink &&
              !serviceDetail.contentDetails.miniProgramCode1 &&
              !serviceDetail.contentDetails.miniProgramCode2 &&
              !serviceDetail.contentDetails.qrCode &&
              !serviceDetail.contentDetails.otherInfo &&
              (!attachmentList || attachmentList.length === 0)
            "
          >
            <img class="empty" src="/static/icon/empty.svg" alt="" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { handleProxy, getServiceDetail } from '@/api/data.js'
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import Navigation from '@/components/navigation.vue'
wx.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
})
const serviceDetail = ref({
  createTime: '2025-08-13 10:57:39',
  description: '',
  homeImage: null,
  id: 511,
  name: '博士后政策',
  parentId: 508,
  parentName: '补贴政策',
  sortOrder: 0,
  status: 1,
  topParentId: 507,
  topParentName: '我是人才',
  type: 'CONTENT',
  updateTime: '2025-08-25 08:45:12',
  contentDetails: {
    id: 13,
    menuId: 321,
    serviceTarget: '来台有就业见习需求的青年',
    policyStandard: '',
    department: '椒江区就业服务中心',
    contact: '',
    handleLink: '',
    qrCode: '',
    otherInfo: '附见习平台清单图片',
    createTime: '2025-07-28 02:22:11',
    updateTime: '2025-07-28 02:22:11',
    attachments:
      '[{"id":1753875488231.1685,"name":"点位导入模板.xlsx","url":"/api/files/2025/07/30/fbf65380-b765-4251-a693-144b8f1296ec.xlsx","size":16977,"type":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}]',
  },
  children: null,
})

// 计算附件列表
const attachmentList = computed(() => {
  if (!serviceDetail.value.contentDetails.attachments) {
    return null
  }
  try {
    const attachments = JSON.parse(serviceDetail.value.contentDetails.attachments)
    return Array.isArray(attachments) ? attachments : null
  } catch (error) {
    console.error('解析附件数据失败:', error)
    return null
  }
})

const viewQRCode = () => {
  if (serviceDetail.value.contentDetails.qrCode) {
    uni.previewImage({
      urls: [handleProxy(serviceDetail.value.contentDetails.qrCode)],
      current: handleProxy(serviceDetail.value.contentDetails.qrCode),
    })
  } else {
    uni.showToast({
      title: '二维码不存在',
      icon: 'none',
    })
  }
}
onLoad((options) => {
  getServiceDetail(options.id).then((res) => {
    serviceDetail.value = res.data.data
  })
})
const gotoMiniProgram = (url) => {
  wx.navigateToMiniProgram({
    shortLink: url,
    fail: (err) => {
      if (err.errMsg.indexOf('cancel') !== -1) {
        return
      }
      if (err.errMsg.indexOf('not found') !== -1) {
        uni.showToast({
          title: '未找到该小程序',
          icon: 'none',
        })
        return
      }
      if (err.errMsg.indexOf('invalid') !== -1) {
        uni.showToast({
          title: '小程序链接无效',
          icon: 'none',
        })
        return
      }
      uni.showToast({
        title: '跳转小程序失败',
        icon: 'none',
      })
    },
  })
}
const copyLink = () => {
  uni.setClipboardData({
    data: serviceDetail.value.contentDetails.handleLink,
    success: () => {
      uni.showToast({
        title: '链接已复制',
        icon: 'none',
      })
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none',
      })
    },
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 打开附件
const openAttachment = (attachment) => {
  // 先下载文件到临时目录
  let white_filetype = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
  let white_image = [
    'jpg',
    'jpeg',
    'png',
    'gif',
    'webp',
    'ico',
    'wbmp',
    'fax',
    'net',
    'rp',
    'jfif',
    'jpe',
    'tiff',
    'tif',
  ]
  let white_media = ['mp3', 'wav', 'flac', 'aac', 'mp4', 'avi', 'wmv', 'mov', 'flv']
  const fileType = getFileType(attachment.name)
  uni.downloadFile({
    url: handleProxy(attachment.url),
    success: (res) => {
      if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        if (white_filetype.indexOf(fileType) != -1) {
          // 使用微信小程序API打开文件
          uni.openDocument({
            filePath: filePath,
            fileType: fileType,
            success: () => {
              console.log('文件打开成功')
            },
            fail: (err) => {
              console.log('文件打开失败:', err)
              uni.showToast({
                title: '无法打开此文件',
                icon: 'none',
              })
            },
          })
        } else if (white_image.indexOf(fileType) != -1) {
          uni.previewImage({
            urls: [filePath],
            longPressActions: {
              itemList: ['发送给朋友', '保存图片', '收藏'],
              success: function (data) {},
              fail: function (err) {
                uni.showToast({
                  title: err.errMsg,
                  icon: 'none',
                })
              },
            },
          })
        } else if (white_media.indexOf(fileType) != -1) {
          wx.previewMedia({
            sources: [
              {
                url: filePath, //图片或者视频所在路径
                type: 'video', //图片为image，视频为video
              },
            ],
            success(res) {
              //预览成功
              // uni.showToast({
              // 	title: "预览成功",
              // 	icon: "none"
              // })
            },
            fail(err) {
              uni.showToast({
                title: err.errMsg,
                icon: 'none',
              })
              //预览失败
            },
          })
        } else {
          uni.showToast({
            title: '不支持打开该类型文件',
            icon: 'none',
          })
        }
      } else {
        uni.showToast({
          title: '文件加载失败',
          icon: 'none',
        })
      }
    },
    fail: () => {
      uni.showToast({
        title: '文件加载失败',
        icon: 'none',
      })
    },
  })
}

// 获取文件类型
const getFileType = (fileName) => {
  const ext = fileName.toLowerCase().split('.').pop()
  const typeMap = {
    pdf: 'pdf',
    doc: 'doc',
    docx: 'docx',
    xls: 'xls',
    xlsx: 'xlsx',
    ppt: 'ppt',
    pptx: 'pptx',
    txt: 'txt',
    jpg: 'jpg',
    jpeg: 'jpeg',
    png: 'png',
    gif: 'gif',
  }
  return typeMap[ext] || 'other'
}

// 判断是否为图片文件
const isImageFile = (fileName) => {
  const imageExtensions = [
    'jpg',
    'jpeg',
    'png',
    'gif',
    'webp',
    'ico',
    'wbmp',
    'fax',
    'net',
    'rp',
    'jfif',
    'jpe',
    'tiff',
    'tif',
  ]
  const ext = fileName.toLowerCase().split('.').pop()
  return imageExtensions.includes(ext)
}

// 获取文件扩展名
const getFileExtension = (fileName) => {
  const ext = fileName.toLowerCase().split('.').pop()
  return ext.toUpperCase()
}

// 获取文件图标样式类
const getFileIconClass = (fileName) => {
  const ext = getFileType(fileName)
  const classMap = {
    pdf: 'file-pdf',
    doc: 'file-word',
    docx: 'file-word',
    xls: 'file-excel',
    xlsx: 'file-excel',
    ppt: 'file-ppt',
    pptx: 'file-ppt',
    txt: 'file-txt',
  }
  return classMap[ext] || 'file-other'
}
</script>

<style lang="scss">
.footer {
  .code {
    display: flex;
    flex-direction: column;
    align-items: center;
    .code-img {
      margin-top: 16rpx;
      width: 320rpx;
      height: 320rpx;
    }
    .code-text {
      margin-top: 8rpx;
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 12px;
      text-align: center;
      color: #969799;
    }
  }

  .attachment {
    margin-top: 16rpx;
    .content {
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 14px;
      color: #646566;
      line-height: 1.5;
    }
  }

  .attachment-list {
    margin-top: 24rpx;
    .attachment-title {
      font-family: PingFang SC;
      font-weight: 500;
      font-style: Medium;
      font-size: 14px;
      line-height: 20px;
      letter-spacing: 0px;
      padding-left: 18rpx;
      position: relative;
      color: #000;
      margin-bottom: 16rpx;
      &::after {
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 24rpx;
        border-radius: 4px;
        content: '';
        background: linear-gradient(0deg, #44d4a8 0%, #30d1e6 100%);
      }
    }
    .attachment-item {
      display: flex;
      align-items: center;
      
      margin-bottom: 16rpx;
      // border-radius: 12rpx;
      background: #f8f9fa;
      border: 1rpx solid #e9ecef;
      transition: all 0.3s ease;
      &:last-child {
        margin-bottom: 0;
      }
      &:active {
        background: #e9ecef;
        transform: scale(0.98);
      }

      .attachment-image-preview {
        width: 80rpx;
        height: 80rpx;
        margin-right: auto;
        margin-left: auto;
        flex-shrink: 0;
        border-radius: 8rpx;
        overflow: hidden;
        border: 1rpx solid #e9ecef;
        .attachment-thumbnail {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .attachment-image-preview-large {
        width: 100%;

        margin: 0 auto;
        flex-shrink: 0;
        border-radius: 12rpx;
        overflow: hidden;
        border: 1rpx solid #e9ecef;
        .attachment-thumbnail-large {
          width: 100%;
          display: block;
        }
      }

      .attachment-icon {
        width: 80rpx;
        height: 80rpx;
        margin-right: 24rpx;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        .file-icon {
          width: 60rpx;
          height: 60rpx;
          border-radius: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 20rpx;
          font-weight: bold;
          color: #fff;
          &.file-pdf {
            background: #ff4757;
          }
          &.file-word {
            background: #2e86de;
          }
          &.file-excel {
            background: #10ac84;
          }
          &.file-ppt {
            background: #ff6348;
          }
          &.file-txt {
            background: #747d8c;
          }
          &.file-other {
            background: #a4b0be;
          }
        }
      }

      .attachment-info {
        flex: 1;
        margin-right: 16rpx;
        overflow: hidden;
      }

      .attachment-name {
        font-family: PingFang SC;
        font-weight: 400;
        font-style: Regular;
        font-size: 14px;
        color: #333333;
        margin-bottom: 8rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .attachment-size {
        font-family: PingFang SC;
        font-weight: 400;
        font-style: Regular;
        font-size: 12px;
        color: #969799;
      }
      .view-text {
        font-family: PingFang SC;
        font-weight: 500;
        font-style: Medium;
        font-size: 12px;
        color: #5291f0;
        flex-shrink: 0;
      }
    }
  }

  .content {
    font-family: PingFang SC;
    font-weight: 400;
    font-style: Regular;
    font-size: 14px;
    color: #646566;
    margin: 16rpx 0;
    word-break: break-all;
    word-wrap: break-word;
    white-space: pre-wrap;
    line-height: 1.5;
  }
  .copy {
    height: 88rpx;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);
    .text {
      font-family: PingFang SC;
      font-weight: 500;
      font-style: Medium;
      font-size: 14px;
      color: #fff;
    }
    .icon {
      width: 32rpx;
      height: 32rpx;
    }
  }
  .link {
    cursor: pointer;
    color: #5291f0;
    text-decoration: underline;
  }
}
.empty-box {
  display: flex;
  .empty {
    width: 320rpx;
    height: 356rpx;
    margin: 10rpx auto;
  }
}
.service-detail {
  background: url('https://api.taishow.cc/talent/api/files/2025/09/01/b1f6d6e0-3289-4838-ad8f-d194415948e1.png')
    no-repeat;
  background-repeat: no-repeat;
  background-size: cover;
  .top {
    padding: 32rpx;
    border-radius: 32rpx;
    background: linear-gradient(180deg, rgba(255, 255, 255, 0.75) 0%, rgba(255, 255, 255, 0) 100%);
    .title {
      font-family: PingFang SC;
      font-weight: 600;
      font-style: Medium;
      font-size: 32rpx;
      color: #323333;
    }
    .tag-list {
      margin-top: 16rpx;
      display: flex;
      gap: 8rpx;
      .tag {
        padding: 0 16rpx;
        text-align: center;
        height: 48rpx;
        line-height: 48rpx;
        border-radius: 8rpx;
        background: #7aabf51a;
        font-family: PingFang SC;
        font-weight: 400;
        font-style: Regular;
        font-size: 24rpx;
        color: #5291f0;
        background: #7aabf51a;
        &:nth-child(1) {
          color: #fff;
          background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);
        }
      }
    }
  }
  .body {
    margin-top: 32rpx;
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    .item {
      position: relative;
      background: linear-gradient(180deg, rgba(255, 255, 255, 0.5) 0%, #ffffff 50%);
      width: 100%;
      border-radius: 24rpx;
      border: 4rpx solid #fff;
      padding-top: 80rpx;
      padding-right: 32rpx;
      padding-bottom: 32rpx;
      padding-left: 32rpx;
      .header {
        position: absolute;
        width: 240rpx;
        height: 80rpx;
        left: -4rpx;
        top: -4rpx;
      }
      .adorn {
        position: absolute;
        right: 0;
        top: 0;
        width: 172rpx;
        height: 88rpx;
        transform: rotateY(180deg);
      }
      .content {
        font-family: PingFang SC;
        font-weight: 400;
        font-style: Regular;
        font-size: 28rpx;
        color: #333333;
      }
    }
  }
}
</style>
